import { useEffect, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  DatePicker,
  Spin,
  Row,
  Col,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import repairService, {
  type PageListReq,
} from "@/api/services/eam/repairService";
import type { EamEquipmentRepair } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import CustomTable from "@/components/grid/CustomTable";
import { CaretRightOutlined, EyeOutlined, SearchOutlined, ToolOutlined } from "@ant-design/icons";
import SingleEquipmentSelect from "@/pages/components/selector/SingleEquipmentSelect";
import dayjs from "dayjs";
import { EamEquipment } from "../equipment/entity";
import EamEquipmentRepairPanel from "./repairPanel";

const { TextArea } = Input;

export default function EamEquipmentRepairPage() {
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    code: undefined,
    equipmentId: undefined,
    repairStatus: undefined,
    urgency: undefined,
    repairOwner: undefined,
    repairResult: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<EamEquipmentRepair[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [reportVisible, setReportVisible] = useState(false);
  const [editingData, setEditingData] = useState<EamEquipmentRepair | null>(
    null
  );
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);
  const [isReportView, setIsReportView] = useState(false);

  const [selectEquipmentVisible, setSelectEquipmentVisible] = useState(false);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const repairStatusOptions = useDictionary("equipment_repair_status");
  const urgencyOptions = useDictionary("urgency_type");
  const repairModeOptions = useDictionary("equipment_repair_type");
  const repairResultOptions = useDictionary("equipment_repair_result");
  const equipmentStateOptions = useDictionary("equipment_use_status");

  const columns: ColumnsType<EamEquipmentRepair> = [
    {
      title: "维修单号",
      width: 180,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "关联单据",
      width: 180,
      key: "relateCode",
      dataIndex: "relateCode",
    },
    {
      title: "维修状态",
      width: 120,
      key: "repairStatus",
      dataIndex: "repairStatus",
      align: "center",
      render: (_, record) => (
        <TableDictTag
          dictCode="equipment_repair_status"
          value={record.repairStatus ?? ""}
        />
      ),
    },
    {
      title: "紧急状态",
      width: 120,
      key: "urgency",
      dataIndex: "urgency",
      align: "center",
      render: (_, record) => (
        <TableDictTag dictCode="urgency_type" value={record.urgency ?? ""} />
      ),
    },
    {
      title: "设备状态",
      width: 120,
      key: "equipmentStatus",
      align: "center",
      dataIndex: "equipmentStatus",
      render: (_, record) => (
        <TableDictTag
          dictCode="equipment_use_status"
          value={record.equipmentStatus ?? ""}
        />
      ),
    },
    {
      title: "设备编码",
      width: 120,
      key: "equipmentCode",
      dataIndex: "equipmentCode",
    },
    {
      title: "设备名称",
      width: 120,
      key: "equipmentName",
      dataIndex: "equipmentName",
    },
    {
      title: "设备类型",
      width: 120,
      key: "equipmentTypeName",
      dataIndex: "equipmentTypeName",
    },
    {
      title: "设备型号",
      width: 120,
      key: "equipmentModel",
      dataIndex: "equipmentModel",
    },
    {
      title: "设备负责人",
      width: 120,
      key: "resourceOwnerName",
      dataIndex: "resourceOwnerName",
    },
    {
      title: "车间",
      width: 120,
      key: "workshopName",
      dataIndex: "workshopName",
    },

    {
      title: "报修时间",
      width: 180,
      key: "requestTime",
      dataIndex: "requestTime",
    },
    {
      title: "报修人",
      width: 120,
      key: "requestUserName",
      dataIndex: "requestUserName",
    },
    {
      title: "送修方式",
      width: 120,
      key: "repairMode",
      dataIndex: "repairMode",
      align: "center",
      render: (_, record) => (
        <TableDictTag
          dictCode="equipment_repair_type"
          value={record.repairMode ?? ""}
        />
      ),
    },
    {
      title: "预计完成时间",
      width: 120,
      key: "estimatedWorkOrderTime",
      dataIndex: "estimatedWorkOrderTime",
    },
    {
      title: "维修开始时间",
      width: 180,
      key: "repairStartTime",
      dataIndex: "repairStartTime",
    },
    {
      title: "维修结束时间",
      width: 180,
      key: "repairFinishTime",
      dataIndex: "repairFinishTime",
    },
    {
      title: "维修责任人",
      width: 120,
      key: "repairOwnerName",
      dataIndex: "repairOwnerName",
    },
    {
      title: "维修结果",
      width: 120,
      align: "center",
      key: "repairResult",
      dataIndex: "repairResult",
      render: (_, record) => (
        <TableDictTag
          dictCode="equipment_repair_result"
          value={record.repairResult ?? ""}
        />
      ),
    },
    {
      title: "执行人",
      width: 120,
      key: "executorName",
      dataIndex: "executorName",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 180,
      render: (_, record) => (
        <Space>
          {record.repairStatus === "request" && (
            <Button type="link" icon={<CaretRightOutlined />} onClick={() => handleStartRepair(record)}>
            开始维修
          </Button>
          )}
          {(record.repairStatus === "in_maintenance" || record.repairStatus === "suspend") && (
            <Button type="link" icon={<ToolOutlined />} onClick={() => handleRepair(record)}>
              维修
            </Button>
          )}
          {(record.repairStatus === "finish" || record.repairStatus === "verify") && (
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewRepair(record)}>
              查看报告
            </Button>
          )}
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    repairService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (eamEquipmentRepair: EamEquipmentRepair) => {
    setEditingData(eamEquipmentRepair);
    form.setFieldsValue(eamEquipmentRepair);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (eamEquipmentRepair: EamEquipmentRepair) => {
    setEditingData(eamEquipmentRepair);
    form.setFieldsValue(eamEquipmentRepair);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: EamEquipmentRepair) => {
    try {
      setSubmitLoading(true);

      const data = {
        ...values,
        id: editingData?.id,
      };
      if (editingData) {
        await repairService.update(data);
        toast.success("更新设备维修单成功");
      } else {
        await repairService.add(data);
        toast.success("创建设备维修单成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await repairService.remove(selectedRowKeys);
      toast.success("删除设备维修单成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const showEquipmentSelect = () => {
    setSelectEquipmentVisible(true);
  };
  const handleSelectEquipment = (item: EamEquipment) => {
    setSelectEquipmentVisible(false);
    form.setFieldsValue({
      equipmentId: item?.id,
      equipmentName: item?.name,
      equipmentCode: item?.code,
      equipmentType: item?.type,
      equipmentTypeName: item.typeName,
      equipmentModel: item?.model,
      equipmentStatus: item?.useStatus,
      resourceOwner: item?.resourceOwner,
      resourceOwnerName: item?.resourceOwnerName,
      workshopId: item?.workshopId,
      workshopName: item?.workshopName,
    });
  };

  // 开始维修
  const handleStartRepair = async (record: EamEquipmentRepair) => {
    try {
      setLoading(true);
      await repairService.startRepair(record.id);
      toast.success("开始维修成功");
      fetchPageList();
    } catch (error) {
      toast.error(`开始维修失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  //维修
  const handleRepair = (eamEquipmentRepair: EamEquipmentRepair) => {
    setEditingData(eamEquipmentRepair);
    setReportVisible(true);
    setIsReportView(false);
  };

  //查看维修报告
  const handleViewRepair = (eamEquipmentRepair: EamEquipmentRepair) => {
    setEditingData(eamEquipmentRepair);
    setReportVisible(true);
    setIsReportView(true);
  };

  const closeReportPanel = () => {
    setReportVisible(false);
    fetchPageList();
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          style={{ display: "flex", flexWrap: "wrap", gap: "16px" }}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="code" label="维修单号" style={{ width: 250 }}>
            <Input allowClear placeholder="请输入维修单号" />
          </Form.Item>

          <Form.Item name="equipmentId" label="设备ID" style={{ width: 250 }}>
            <Input allowClear placeholder="请输入设备ID" />
          </Form.Item>

          <Form.Item
            name="repairStatus"
            label="维修状态"
            style={{ width: 250 }}
          >
            <Select
              options={repairStatusOptions}
              allowClear
              placeholder="请选择维修状态"
            />
          </Form.Item>

          <Form.Item name="urgency" label="紧急状态" style={{ width: 250 }}>
            <Select
              options={urgencyOptions}
              allowClear
              placeholder="请选择紧急状态"
            />
          </Form.Item>

          <Form.Item
            name="repairOwner"
            label="维修责任人"
            style={{ width: 250 }}
          >
            <Input allowClear placeholder="请输入维修责任人" />
          </Form.Item>

          <Form.Item
            name="repairResult"
            label="维修结果"
            style={{ width: 250 }}
          >
            <Select
              options={repairResultOptions}
              allowClear
              placeholder="请选择维修结果"
            />
          </Form.Item>

          <Form.Item style={{ width: 250, marginLeft: 15 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑设备维修单" : "新增设备维修单"}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button
                type="primary"
                loading={submitLoading}
                onClick={() => form.submit()}
              >
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="code" label="维修单号">
                <Input placeholder="请输入维修单号" disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="relateCode" label="关联单据">
                <Input placeholder="请输入关联单据" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="equipmentId" label="设备" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="equipmentCode" label="设备编码">
                <Input.Search
                  placeholder="请选择设备"
                  allowClear
                  enterButton={<SearchOutlined />}
                  onSearch={showEquipmentSelect}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="equipmentName" label="设备名称">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="equipmentModel" label="设备型号">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="equipmentStatus" label="设备状态">
                <Select options={equipmentStateOptions} disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="equipmentTypeName" label="设备类型">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="resourceOwner" label="设备负责人" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="resourceOwnerName" label="设备负责人">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="workshopId" label="车间" hidden>
                <Input disabled />
              </Form.Item>
              <Form.Item name="workshopName" label="车间">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="urgency"
                label="紧急状态"
                rules={[
                  {
                    required: true,
                    message: "请填写紧急状态",
                  },
                ]}
              >
                <Select options={urgencyOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="repairMode"
                label="送修方式"
                rules={[
                  {
                    required: true,
                    message: "请填写送修方式",
                  },
                ]}
              >
                <Select options={repairModeOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="estimatedWorkOrderTime"
                label="预计完成时间"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
          </Row>
          {isView && (
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="requestUser" label="报修人" hidden>
                  <Input disabled />
                </Form.Item>
                <Form.Item name="requestUser" label="报修人">
                  <Input disabled />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="requestTime"
                  label="报修时间"
                  getValueFromEvent={(value) => {
                    return value ? value.format("YYYY-MM-DD HH:mm:ss") : null;
                  }}
                  getValueProps={(value) => ({
                    value: value
                      ? dayjs(value, "YYYY-MM-DD HH:mm:ss")
                      : undefined,
                  })}
                >
                  <DatePicker
                    style={{ width: "100%" }}
                    format="YYYY-MM-DD HH:mm:ss"
                    onChange={(date) =>
                      date ? date.format("YYYY-MM-DD HH:mm:ss") : null
                    }
                    disabled
                  />
                </Form.Item>
              </Col>
            </Row>
          )}

          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="symptoms"
                label="故障描述"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
                rules={[
                  {
                    required: true,
                    message: "请填写故障描述",
                  },
                ]}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <SingleEquipmentSelect
          open={selectEquipmentVisible}
          onCancel={() => setSelectEquipmentVisible(false)}
          onOk={(item) => handleSelectEquipment(item)}
        />
      </Drawer>

      <EamEquipmentRepairPanel
        visible={reportVisible}
        isView={isReportView}
        repair={editingData as EamEquipmentRepair}
        onClose={closeReportPanel}
      />
    </Spin>
  );
}
